import axios from 'axios'
import store from '../store/index'
import qs from 'qs'
import { Toast } from 'vant'

const service = axios.create({
  baseURL: store.getters.serverUrl
})

service.interceptors.request.use(
  (config) => {
    if (config.params === undefined) {
      config.params = {}
    }
    // config.headers= {'X-Requested-With': 'XMLHttpRequest'}

    // console.log('store.getters==>', store.getters)

    if (config.method === 'post' || config.method === 'POST') {
      if (
        Object.prototype.toString.call(config.params) === '[object FormData]'
      ) {
        config.data = config.params
      } else {
        config.data = qs.stringify(config.params)
      }
      config.params = {}
    }

    // config.url = store.getters.serverUrl + config.url;

    //是否启用token
    if (store.getters.isUseDebugToken) {
      config.params.ecafeToken = store.getters.ecafeToken
    }

    return config
  },
  (error) => {
    console.log(error) // for debug
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    try {
      if (res.code === '99') {
        alert(res.message)
        return Promise.reject('error')
      } else if (res.code === '-1') {
        Toast.fail(res.message)
        return response.data
      } else {
        return response.data
      }
    } catch (err) {
      console.error(err)
    }
  },
  (error) => {
    console.log('err' + error) // for debug
    let errorMessage = error.message
    if (errorMessage === 'Network Error') {
      errorMessage = '网络故障'
    } else if (errorMessage.indexOf('timeout of ') !== -1) {
      errorMessage = '连接超时'
    } else if (errorMessage === 'Request failed with status code 404') {
      errorMessage = '后台接口404'
    } else if (errorMessage === 'Request failed with status code 500') {
      errorMessage = '服务器内部错误' //"数据量过多，请电联管理员：020-38889836协助解决！"//
    } else {
      if (
        error.response.data.message.indexOf('未初始化业务系统用户信息') !== -1
      ) {
        errorMessage = error.response.data.message
      } else {
        errorMessage = '服务器错误' //"数据量过多，请电联管理员：020-38889836协助解决！"//
      }
    }
    Toast.error(errorMessage)
    return Promise.reject(error)
  }
)

export default service
